// import './commonJs/call_1.3'
import api from '../../../api/api';
import message from '@wanhu/antd-legacy/lib/message'
// 测试环境
// let params = {
//     "client_id": "d9ac577ec0664f4ea84eec45a30b46e4",
//     "client_secret": "256d2eb41a7e4860ba1449055a70ee7c",
//     "companyId": "958effa150e6415f8a061b1fe0340931",
//     "appId": "d9ac577ec0664f4ea84eec45a30b46e4",
//     "agentId": "",//"41421965554a4757870b20490dd08bc8",//"2df0ef081b6b4f1a9cec59fc074fdbe8",//
//     "groupId" : "",//"958effa150e6415f8a061b1fe0340931_1",//$("#groupId").val()?$("#groupId").val():'',
//     "voipAccount":"",//"148860000",//'13691451178',
//     "callWay": 1
// }

// 生产环境1
let params = {
    "client_id": "a73edc5318cd466ab2bfbe5cc1bc62fd",
    "client_secret": "3e3ac1100011479a8110aa72e13369dd",
    "companyId": "a251329794ba4776a5b5cca28882a134",
    "appId": "a73edc5318cd466ab2bfbe5cc1bc62fd",
    "agentId": "",
    "groupId" :"",
    "voipAccount": "",
    "callWay": 2
}
let callId = "";//外呼id，外呼成功获得，挂断外呼需要。
let phone = "";//电话号码
let address = "";//地区
let name = "";//姓名
let ifTheme = false;//是否是任务界面，是true
let isListen="",patientId = "",taskId="",taskType="",taskReclassify="",subject="",content="",isMember=false,callType = 1,istask="";


// 以下可以开启查看修改电话条样式
// let callData = {
//     callInfos:{
//         callType:1,//1:外呼中
//         phone:"13161001244",//呼叫电话号码
//         address:"北京 北京",//地址城市+区
//         name:"测试名",//姓名
//         callId:"res.callId",
//     },
// }
// setTimeout(function(){
//     localStorage.setItem("callInfo",JSON.stringify(callData));
// },1500)

let getCallNumberWai = ""
let getAgentIdNum = ""
let getUserInfo = {}
const getCallNumberWaiFun =async function() {
    const userInfo = await api.getUserInfo()
    getUserInfo = userInfo
    getAgentIdNum = await api.getAgentId(userInfo.user)
    getCallNumberWai = await api.getCallNumber(params.appId)
    if(getAgentIdNum && getAgentIdNum.length>5){
        params.agentId = getAgentIdNum || ""
    }else{
        getAgentIdNum = ""
        return //如果有agentId，继续，没有就停止
    }
    if(getCallNumberWai && getCallNumberWai.length>0){
        getCallNumberWai = getCallNumberWai[0].call_number || ""
    }else{
        getCallNumberWai = ""
    }
    window.zcVertoServ.ininServ(params,statusFunc);
    getToken()
}
isListen = ""
localStorage.setItem("popDiogTask","");
var statusFunc =async function(res){
    //websocket状态变化回调函数  此函数需初始化时传入
    localStorage.setItem("popDiogTask","");
    var tem={};
    console.log("websocket回调statusFunc",res)
    if(res && res.data){
      tem = JSON.parse(res.data);
      if(tem.msgType){
        let phoneOut = tem.callee?tem.callee:"";
        let phoneIn = tem.caller?tem.caller:"";
        let phoneUser = tem.callee?tem.callee:"";
        let addressZc = tem.numberProvice+tem.numberCity;
        // 挂断电话
        let callDataPhoneOff = {
            callInfos:null,
        }
        // 挂断电话弹出备注录入
        let themeShowStr = 'themeShowStr'
        // 呼出电话中
        let callDataOut = {
            callInfos:{
                callType:1,//1:呼出中
                phone:phoneOut,//呼叫电话号码
                address:addressZc,//地址城市+区
                name:name,//姓名
                callId:callId,
            },
        }
        // 呼入电话中
        let callDataIn = {
            callInfos:{
                callType:2,//2:呼入中
                phone:phoneIn,
                address:addressZc,
                name:name,
                callId:callId,
            },
        }
        // 呼入电话接听中
        let callDataInOn = {
            callInfos:{
                callType:3,//3:呼入中
                phone:phoneIn,
                address:addressZc,
                name:name,
                callId:callId,
            },
        }
        // 呼出电话接听中
        let callDataInOnHC = {
            callInfos:{
                callType:3,//3:呼入中
                phone:phoneUser,
                address:addressZc,
                name:name,
                callId:callId,
            },
        }
        if(tem && tem.direction){
            callType = tem.direction
        }
        // 被人顶掉了
        let callRepeat = "callRepeat"
        switch(tem.msgType){
            case 'onLine':
                // message.success("已上线");
                localStorage.setItem("callIsOff","");
                break;
            case 'repeat'://被顶掉了
                message.success(tem.msg);
                localStorage.setItem("callIsOff",JSON.stringify(callRepeat));
                break;
            case 'AgentStateBusy':
                if(tem.agentState == -1){
                    localStorage.setItem("callIsOff","callRepeat");
                }
                break;
            case 'PhoneStateAgentRing':
                isListen = ""
                if(tem.direction == "0"){
                    callType = 0
                    name = ""
                    callId = tem.callId
                    taskId=""
                    taskType=""
                    taskReclassify=""
                    patientId = ""
                    subject = ""
                    content = ""
                    // message.success('有电话进入');
                    localStorage.setItem("callInfo",JSON.stringify(callDataIn));
                    phone = phoneIn
                    isNewMemberFun(phoneIn,callDataIn)
                } else {
                    sendCallInfoFun()
                }
                break;
            case 'PhoneStateAgentConnected'://坐席电话接听了
                if(tem.direction == "0"){
                    // message.success('电话接听');
                    isListen = true
                    localStorage.setItem("callInfo",JSON.stringify(callDataInOn));
                }else{
                    localStorage.setItem("callInfo",JSON.stringify(callDataOut));
                }
                break;
            case 'PhoneStateUserConnected'://用户电话接听
                // message.success('用户已接听');
                localStorage.setItem("callInfo",JSON.stringify(callDataInOnHC));
                break;
            case 'StartService': //通话开始，呼入到达智齿系统或者呼出时开始呼叫
                localStorage.setItem("callInfo",JSON.stringify(callDataOut));
                break;
            case 'PhoneStateDisConnected':
                // message.success('用户已挂断');
                localStorage.setItem("callInfo",JSON.stringify(callDataPhoneOff));
                sendCallInfoFun("over")
                localStorage.setItem("themeShowStr",themeShowStr);
                subject=""
                content = ""
                break;
            case 'AgentStateIdle':
                subject=""
                content = ""
                taskId=""
                taskType=""
                taskReclassify=""
                localStorage.setItem("callInfo", JSON.stringify(callDataPhoneOff));
                break;
            case 'StopService':
                // message.success('通话结束');
                localStorage.setItem("callInfo",JSON.stringify(callDataPhoneOff));
                localStorage.setItem("themeShowStr",themeShowStr);
                if(tem.direction == "0" && isListen){
                    localStorage.setItem("popDiogTask","popDiogTask");
                }
                sendCallInfoFun("over")
                subject=""
                content = ""
                taskId=""
                taskType=""
                taskReclassify=""
                break;
            default:
                if(!!tem.callId){
                    // currentCall=tem;
                }
            break;
        }
      }
    }
}

//获取token方法：
const getTokenCallBack = function(res){
    if(res.access_token){
        window.zcVertoServ.queryAgentState(queryAgentStateCallBack)
    }
}
var getToken = function () {
    window.zcVertoServ.getToken(getTokenCallBack);
}

// 重载
const queryAgentStateCallBack = function(res){
    const getNowCallType = localStorage.getItem("lastCallType");
    if(res.retCode==='000000' && res.item.agentState >= 0){
        window.zcVertoServ.reConnect();
        localStorage.setItem("callIsOff","");
        if (getNowCallType === "yes") {
            setTimeout(function () {
                updateAgentState(1)
            }, 2000)
        }
        else if (!getNowCallType) {
            setTimeout(function(){
                updateAgentState(-1)
            },2000)
        }
        console.log(1)
    }else{
        console.log(2)
        // if(res.item.agentState)
        window.zcVertoServ.reConnect();
        if(getNowCallType === "yes"){
            setTimeout(function () {
                updateAgentState(1)
            },2000)
        }else{
            setTimeout(function(){
                updateAgentState(-1)
            },2000)
        }
        // updateAgentState(-1)
        // queryAgentState()
        // agentOnWork(-1)
    }
}

//坐席下班
const loginoutCallBack = function(res){
    localStorage.setItem("callIsOff","callRepeat");
}
export const loginout = function () {
    window.zcVertoServ.agentLoginout(loginoutCallBack);
}

//坐席上班（上班后为空闲状态）
var agentOnWorkCallBack = function(res){
    if(res.retCode == "000000"){
        // queryAgentState()
    }
}
var agentOnWork = function (agentState) {
    var data = {
        "displayNumber": getCallNumberWai?getCallNumberWai:"02281944945",
        "agentState":agentState
    }
    window.zcVertoServ.agentLogin(data,agentOnWorkCallBack)
}
export const loginoutexport = function () {
    updateAgentState(-1)
}

// agentOnWork(1)
//坐席外呼
var callback = function(res){
    if(res.retCode == "000000"){
        // message.success("呼叫中");
        callId = res.callId;
        let callData = {
            callInfos:{
                callType:1,//1:外呼中
                phone:phone,//呼叫电话号码
                address:address,//地址城市+区
                name:name,//姓名
                callId:res.callId,
                ifTheme:ifTheme,//是否任务界面
            },
        }
        localStorage.setItem("callInfo",JSON.stringify(callData));
    }else{
        message.error(res.retMsg?res.retMsg:"网络异常，请刷新后重试");
    }
}
export const callOut = function (phoneNum,adrs,names,theme,getpatientId,gettaskId,gettaskType,gettaskReclassify,getSubject,getContent) {
    // console.log("外拨电话参数",phoneNum,adrs,names)
    phone = phoneNum//"13161001269"//phoneNum;//13161001269//
    address = ""//adrs.provinceName+adrs.areaName;
    name = names;
    ifTheme = theme
    patientId = getpatientId
    taskId = gettaskId || ""
    taskType = gettaskType || ""
    taskReclassify = gettaskReclassify || ""
    subject = getSubject || ""
    content = getContent || ""
    if (gettaskType == "0") {
        taskType = "0"
    }
    console.log(222,taskType,gettaskType)
    callType = 1
    var data = {
        "displayNumber": getCallNumberWai?getCallNumberWai:"02281944945",
        "destinationNumber": phone,
        // "params": "test" // 非必填，参数会在推送的通话记录中显示
    }
    if(!getAgentIdNum){
        message.error("未绑定坐席账号或坐席忙碌，无法发起外呼");
        return
    }
    window.zcVertoServ.agentCallOut(data,callback);
}
// callOut()
//坐席挂断
const agentHangUpCallBack = function(res){
    if(res.retCode == "000000"){
        let callData = {
            callInfos:null,
        }
        localStorage.setItem("callInfo",JSON.stringify(callData));
    }else{
        let callData = {
            callInfos:null,
        }
        localStorage.setItem("callInfo",JSON.stringify(callData));
    }
}
export const agentHangUp = function () {
	var data = {
	    "callId": callId
    }
    window.zcVertoServ.agentHangUp(data,agentHangUpCallBack);
}


// 缓存原来“保存数据”方法对象
var orignalSetItem = localStorage.setItem;
// 覆盖原来“保存数据”的方法
localStorage.setItem = function(key,newValue){
    // 创建一个自定义事件对象，名字为 setItemEvent
    var setItemEvent = new Event("setItemEvent");
    // 给事件添加属性
    setItemEvent.newValue = newValue;
    // 触发事件
    window.dispatchEvent(setItemEvent);
    // 触发原来的 localStorage存储 数据的方法,这个是关键，不能使用 localStorage.setItem方法，否则死循环，会内存溢出的
    orignalSetItem.apply(this,arguments);
}

//坐席接听
export const listen = function () {
    // 接听函数无需回调
    console.log('接听')
    isListen = true
	window.zcVertoServ.agentListen();
}
// 查询坐席状态
const getqueryAgentStateCallBack = function(res){
    if(res.item.agentState == -1){
        localStorage.setItem("callIsOff","callRepeat");
        // loginout()
        return
    }
    if(res.item.agentState == 1){
        // agentOnWork(1)
        // window.zcVertoServ.reConnect();
    }
}
var queryAgentState = function () {
    window.zcVertoServ.queryAgentState(getqueryAgentStateCallBack);
}
//坐席状态修改
const updateAgentStateCallBack = function (res) {
    console.log("进了修改状态", res)
    if (res.retCode == "000000") {
        // queryAgentState()
    } else if (res.retCode == "200011") {
        agentOnWork(1)
        // message.error(res.retMsg)
    } else {
        console.log("进了else", res)
        if (res.retCode == "200011") {
            agentOnWork(1)
            return
        }
        agentOnWork(1)
        message.error(res.retMsg)
    }
}
export const updateAgentState = function (agentState){
    var data = {
        // agentState： 0-上班后置于忙碌，1-上班并置位空闲（默认情况），-1-离线，
        "agentState": agentState
    }
    window.zcVertoServ.updateAgentState(data,updateAgentStateCallBack);
}
// 触发非任务界面弹起录入主题，然后拨打电话
export const themeShow = function(phoneNum,adrs,names,theme,getpatientId,gettaskId,gettaskType,gettaskReclassify,getSubject,getContent){
    // console.log("外拨电话参数",phoneNum,adrs,names)
    phone = phoneNum//"13161001269"//phoneNum;//13161001269//
    address = adrs.provinceName+adrs.areaName;
    name = names;
    ifTheme = true
    patientId = getpatientId
    taskId = gettaskId || ""
    taskType = gettaskType || ""
    taskReclassify = gettaskReclassify || ""
    subject = getSubject || ""
    content = getContent || ""
    let callData = {
        callInfos:{
            callType:1,//1:外呼中
            phone:phone,//呼叫电话号码
            address:address,//地址城市+区
            name:name,//姓名
            callId:callId,
            ifTheme:ifTheme,//是否任务界面
            isthemePop:true,
        },
    }
    if(!getAgentIdNum){
        message.error("未绑定坐席账号或坐席忙碌，无法发起外呼");
        return
    }
    localStorage.setItem("callInfo",JSON.stringify(callData));
}
// 非任务界面电话条的拨打电话
export const callBtn = function(getsubject,getcontent){
    subject = getsubject
    content = getcontent
    callOut(phone,address,name,false,patientId,taskId,taskType,taskReclassify,subject,content)
}

export const exportsendCallInfoFun =async function(getsubject,getcontent){
    subject = getsubject
    content = getcontent
    try{
        await sendCallInfoFun()
        return true
    }catch(err){
        return false
    }

}
export const exportsendCallInfoFunInit =async function(getsubject,getcontent){
    subject = getsubject
    content = getcontent
}

const sendCallInfoFun = debounce(async function(){
    const data = {
        "callId":callId,//智齿呼叫id
        "userId":getUserInfo.user,//crm登陆用户id
        "patientId":patientId,//会员ID
        "patientName":name,//会员姓名
        "phone":phone,//电话号码
        "taskId":taskId,//工单id
        "taskType":taskType,//工单类型
        "taskReclassify":taskReclassify,//工单第二类型
        "subject":subject || "",//主题
        "content":content || "",//内容
        "callType":callType,//呼出还是呼入
    }
    try{
        if(callId){
            const sendCallInfo = await api.sendCallInfo(data)
            return "1"
        }
    } catch(res){
        message.error("发送拨号信息失败")
        return false
    }
},2000)

// 防抖 先立即执行，再等2秒
function debounce(func, wait) {
    let timeout
    return function () {
      if (timeout) { clearTimeout(timeout) }
      let callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) {
        func.apply(this)
      }
    }
  }

const isNewMemberFun =async function(iphone,iinfo){
    if(iphone){
        phone = iphone
    }
    // 判断是否为新会员
    let params = {
        where: {
            phone:phone
        },
        skip: 0,
        limit: 1,
        count: 1
    }
    const isNewMember = await api.searchPatientCount(params)
    if(isNewMember.list && isNewMember.list.length>0 && iinfo){
        name = isNewMember.list[0].name
        patientId = isNewMember.list[0].id
        let callInfosIn = iinfo
        callInfosIn.callInfos.name = name
        localStorage.setItem("callInfo",JSON.stringify(callInfosIn));
    }else{
        let callInfosIn = iinfo
        callInfosIn.callInfos.name = ""
        localStorage.setItem("callInfo",JSON.stringify(callInfosIn));
    }
    await sendCallInfoFun()
    return isNewMember
}

export const importisNewMemberFun =async function(iphone){
    if(iphone){
        phone = iphone
    }
    // 判断是否为新会员
    let params = {
        where: {
            phone:phone
        },
        skip: 0,
        limit: 1,
        count: 1
    }
    const isNewMember = await api.searchPatientCount(params)
    if(isNewMember.list && isNewMember.list.length>0){
        name = isNewMember.list[0].name
        patientId = isNewMember.list[0].id
        await sendCallInfoFun()
    }
}
// 录入完备注后点击提交重置备注主题和内容
export const importMemberThemeInit = function(themeVal,themeRemark){
    subject = themeVal || ""
    content = themeRemark || ""
}
// 导入againtId是否还存在
export const importIsAgaintFun =async function(){
    const userInfo = await api.getUserInfo()
    getUserInfo = userInfo
    getAgentIdNum = await api.getAgentId(userInfo.user)
}
// 导出是否为会员
export const exportIsMember =async function(){
    // const isNewMember = await isNewMemberFun()
    if(patientId){
        return true
    }else{
        return false
    }
}
// 导出patientId
export const exportPatientId = function(){
    return patientId
}
// 导出电话
export const exportPhone = function(){
    return phone
}
// 导出taskType，区分是否任务界面发起的通话
export const exportTaskType = function(){
    return taskType
}
// 通过时间戳判断当前是刷新还是关闭窗口 start
let getOldTime = +localStorage.getItem("lastestLeaveTime");
let getNowTime = +(new Date().getTime());
const ishttps = 'https:' == document.location.protocol ? true: false;
if(ishttps){
    if(getOldTime && (getNowTime - getOldTime < 10000)){
        getCallNumberWaiFun()
    }else{
        window.localStorage.setItem('lastCallType',"no");
        getCallNumberWaiFun()
    }
}

window.onbeforeunload=function(e){
    const getPhoneType = localStorage.getItem('callOnOff')
    let getcallInfoLoad = localStorage.getItem("callInfo")
    if(getcallInfoLoad && getcallInfoLoad.indexOf("callInfos") != -1){
        let getCallInfo = JSON.parse(getcallInfoLoad);
        if(getCallInfo && (typeof getCallInfo=='object') && getCallInfo.callInfos && getCallInfo.callInfos.ifTheme){
            let callDataPhoneOff = {
                callInfos:null,
            }
            localStorage.setItem("callInfo",JSON.stringify(callDataPhoneOff));
        }
    }
    if(getPhoneType === "on"){
        window.localStorage.setItem('lastCallType',"yes");
    }else{
        window.localStorage.setItem('lastCallType',"no");
    }
    window.localStorage.setItem('lastestLeaveTime', new Date().getTime());
    // updateAgentState(-1)
// 　　 var e = window.event||e;
// 　　 e.returnValue = "等等等";
}
// 通过时间戳判断当前是刷新还是关闭窗口 end
